import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 此处无需手动为 URL 添加 "/api" 前缀，因 axios 已通过 baseURL 统一处理，
    // 若后续某些请求需要完全自定义地址，可自行在调用处传入完整 URL。

    // 可以在这里添加token等认证信息
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    
    // 如果后端返回的是统一格式的数据
    if (data.code !== undefined) {
      if (data.code === 200) {
        return data.data
      } else {
        console.error(data.message || '请求失败')
        return Promise.reject(new Error(data.message || '请求失败'))
      }
    }
    
    return data
  },
  (error) => {
    let message = '网络错误'
    
    if (error.response) {
      const { status, data } = error.response
      switch (status) {
        case 400:
          message = data.message || '请求参数错误'
          break
        case 401:
          message = '未授权，请重新登录'
          // 可以在这里处理登录过期
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data.message || '请求失败'
      }
    } else if (error.request) {
      message = '网络连接失败'
    }
    
    console.error(message)
    return Promise.reject(error)
  }
)

// 封装GET请求
export const get = <T = any>(url: string, params?: any, config?: any) => {
  return request.get<any, T>(url, { params, ...config })
}

// 封装POST请求
export const post = <T = any>(url: string, data?: any, config?: any) => {
  return request.post<any, T>(url, data, config)
}

// 封装PUT请求
export const put = <T = any>(url: string, data?: any, config?: any) => {
  return request.put<any, T>(url, data, config)
}

// 封装DELETE请求
export const del = <T = any>(url: string, config?: any) => {
  return request.delete<any, T>(url, config)
}

export default request 